import axios from 'axios'
import { Message, Loading } from 'element-ui';
import router from '../models/router'

axios.defaults.baseURL = 'http://localhost:3000';

let loading;
const startLoading = () => {
  loading = Loading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0,0,0,0.7)'
  })
}
const endLoading = () => {
  loading.close();
}

// 请求拦截
axios.interceptors.request.use(config => {
  startLoading();
  // token
  if (localStorage.token) {
    config.headers.Authorization = localStorage.token;
  }
  return config;
}, error => {
  return Promise.reject(error);
})

// 响应拦截
axios.interceptors.response.use(response => {
  endLoading();
  return response;
}, error => {
  endLoading();
  // 获取错误状态码
  const { status } = error.response;
  // 处理token过期等
  if (status === 403) {
    Message.error(error.response.data.message);
    localStorage.removeItem('token');
    router.push('/login');
  } 
  // 登录，注册错误
  else if (status === 404) {
    Message.error(error.response.data.message);
  } else {
    Message.error( error.message || error.response.data);
  }
  return Promise.reject(error);
})

export default axios;
